package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    private EmployeeMapper employeeMapper;

    @Autowired
    public void setEmployeeMapper(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
    }

    @Override
    public void save(Employee employee, Long[] ids) {
        employee.setStatus(true);

        employeeMapper.insert(employee);

        //处理中间表(关联关系)
        if (ids != null && ids.length > 0) {
            for (Long rid : ids) {
                employeeMapper.insertRelation(employee.getId(), rid);
            }
        }

    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //删除关系
        employeeMapper.deleteRelation(employee.getId());
        //关联关系
        //处理中间表(关联关系)
        if (ids != null && ids.length > 0) {
            for (Long rid : ids) {
                employeeMapper.insertRelation(employee.getId(), rid);
            }
        }


    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        //调用分页插件方法,准备分页
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());//当前页,每页显示数量
        //调用自己写的sql,不需要写limit
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<Employee>(employees);
    }

    private static final Long Time = 1000*10*1L;

    @Override
    public Employee login(String username, String password) {
        int number = UserContext.getNumber();
        if (number<1){
            long now = System.currentTimeMillis();
            if (now - UserContext.getTime()<Time){
                long ll = (Time - (now - UserContext.getTime()))/1000;
                throw new LogicException("您被锁住了,还有"+ll+ "秒");
            }
            throw new LogicException("你被锁住了");
        }
        if (!StringUtils.hasText(username)) {
            throw new LogicException("用户名不能为空");
        }
        if (!StringUtils.hasText(password)) {
            throw new LogicException("密码不能为空");
        }
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) {
            throw new LogicException("用户名或密码错误");
        }
        return employee;
    }

    @Override
    public Employee selectByUsername(String username) {
        return employeeMapper.selectByUsername(username);
    }

    @Override
    public Workbook exportXls() {
        //查询所有的员工数据
        List<Employee> employees = employeeMapper.selectAll();
        //创建工作簿excel
        Workbook workbook = new HSSFWorkbook();
        //创建工作表
        Sheet sheet = workbook.createSheet("通讯录");
        //创建标题行
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("姓名");
        row.createCell(2).setCellValue("邮箱");
        row.createCell(3).setCellValue("年龄");

        for (int i = 0; i < employees.size(); i++) {
            //创建行
            row = sheet.createRow(i + 1);
            //获取员工
            Employee employee = employees.get(i);
            //创建单元格
            row.createCell(0).setCellValue(employee.getUsername());
            row.createCell(1).setCellValue(employee.getName());
            row.createCell(2).setCellValue(employee.getEmail());
            if (employee.getAge() != null) {
                row.createCell(3).setCellValue(employee.getAge());
            }
        }

        return workbook;
    }

    @Override
    public void importXls(MultipartFile file) throws IOException {
        //读取上传的文件,并且封装为poi对象
        Workbook workbook = new HSSFWorkbook(file.getInputStream());
        //读取工作表
        Sheet sheet = workbook.getSheetAt(0);
        //读取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            //读取行
            Row row = sheet.getRow(i);
            Employee employee = new Employee();
            employee.setUsername(row.getCell(0).getStringCellValue());
            employee.setName(row.getCell(1).getStringCellValue());
            employee.setEmail(row.getCell(2).getStringCellValue());
            employee.setAge((int) row.getCell(3).getNumericCellValue());
            employee.setPassword("8888888");
            employeeMapper.insert(employee);
        }

    }

    @Override
    public Employee updatePassword(String oldPassword, String newPassword) {
        Employee employee = UserContext.getCurrentUser();
        if (!(employee.getPassword().equals(oldPassword))) {
            throw new LogicException("原密码错误");
        }
        employeeMapper.updatePwd(employee.getId(),newPassword);
        return employee;
    }

    @Override
    public void reset(Long id) {
        employeeMapper.reset(id);
    }

    @Override
    public void setStatus(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);
        if (employee.isStatus()){
            employeeMapper.remove(id);
        }else{
            employeeMapper.recover(id);
        }
    }
}
